package com.xiaodou.mjf.web.xface.user.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xiaodou.mjf.application.core.manager.AccountManager;
import com.xiaodou.mjf.application.core.service.AccountService;
import com.xiaodou.mjf.application.core.service.BankCardCashioService;
import com.xiaodou.mjf.application.core.service.DepositService;
import com.xiaodou.mjf.application.core.service.NotesBookService;
import com.xiaodou.mjf.application.core.service.WithdrawalService;
import com.xiaodou.mjf.application.fee.manager.FeeManager;
import com.xiaodou.mjf.application.user.manager.MemberManager;
import com.xiaodou.mjf.application.user.service.MemberSecurityService;
import com.xiaodou.mjf.application.user.service.MemberService;
import com.xiaodou.mjf.application.user.utils.MemberUtils;
import com.xiaodou.mjf.entity.core.Account;
import com.xiaodou.mjf.entity.core.BankCardCashio;
import com.xiaodou.mjf.entity.core.Deposit;
import com.xiaodou.mjf.entity.core.NotesBook;
import com.xiaodou.mjf.entity.core.Withdrawal;
import com.xiaodou.mjf.entity.user.Member;
import com.xiaodou.mjf.entity.user.MemberSecurity;
import com.xiaodou.mjf.infrastructure.common.controller.ApiController;
import com.xiaodou.mjf.infrastructure.common.utils.DateUtils;
import com.xiaodou.mjf.infrastructure.common.utils.Encrypt;
import com.xiaodou.mjf.infrastructure.common.utils.StringUtils;
import com.xiaodou.mjf.infrastructure.payment.RZContents;
import com.xiaodou.mjf.web.xface.common.ResultCode;

@RestController
@RequestMapping("v1/user")
public class FundController extends ApiController {
	
	@Resource
	DepositService depositService;
	@Resource
	MemberManager memberManager;
	@Resource
	MemberService memberService;
	@Resource
	AccountService accountService;
	@Resource
	NotesBookService notesBookService;
	@Resource
	MemberSecurityService memberSecurityService;
	@Resource
	WithdrawalService withdrawalService;
	@Resource
	AccountManager accountManager;	
	@Resource
	FeeManager feeManager;
	@Resource
	BankCardCashioService bankCardCashioService;
	/**
	 * 充值处理
	 * @param id 
	 * @param uid 客户ID
	 * @param bankName 银行名称
	 * @param bankCardNumber 银行卡号
	 * @param amount 充值金额
	 * @return
	 */
	@RequestMapping("my/deposit")
	public Map<String, Object> deposit(			
			@RequestHeader(required = false) String uid,
			@RequestParam(value="bank_name", required = false) String bankName, 
			@RequestParam(value="card_number", required = false) String bankCardNumber,
			String amount) {
		if (StringUtils.isBlank(uid) || StringUtils.isBlank(bankCardNumber) || StringUtils.isBlank(amount)) {
			return failure(ResultCode.MISSING_PARAMS);
		}
		
		try {
			//插入deposit表
			//返回用户信息，获取户名
			Member member = memberService.get(uid); 
			//获取account_id
			Account account = accountService.getInfoBymemberId(uid);
			//格式化当前时间,得到后加6位随机数
			Date date = DateUtils.getCurrentTime();
			SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
			String serialNumber = df.format(date).toString() + String.valueOf(Math.random()).substring(2,8);
			Deposit deposit = new Deposit();
			//美疯啦金服渠道
			deposit.setChannelId("10210001");
			deposit.setSerialNumber(serialNumber);
			deposit.setMemberId(uid);
			deposit.setAccountId(account.getId());
			deposit.setCardNumbert(bankCardNumber);
			deposit.setAccountTitle(member.getRealName());
			deposit.setAmount(Double.parseDouble(amount));
//			depositService.save(deposit);
			
			//更新account表内的可用余额和账面余额
			account.setBookBalance(account.getBookBalance()+Double.parseDouble(amount));
			account.setAvaliableBalance(account.getAvaliableBalance()+Double.parseDouble(amount));
//			accountService.save(account);
			
			//插入notes_book表
			NotesBook notesBook = new NotesBook();
			notesBook.setAccount(account.getNumber());
			//充值表示为D
			notesBook.setDrcr(NotesBook.DR);
			notesBook.setAmount(Double.parseDouble(amount));
			notesBook.setBalance(account.getBookBalance());
			notesBook.setCardNumber(bankCardNumber);
			notesBook.setSerialNumber(serialNumber);
			notesBook.setTxnDate(DateUtils.getCurrentTime());
			notesBook.setType(NotesBook.TYPE_DEPOSIT);
//			notesBookService.save(notesBook);
			memberManager.deposit(deposit, account, notesBook);
			
		}  catch (Exception e) {
			logger.error(e.toString());
			return failure(ResultCode.DEPOSIT_ERROR);
		}
		
		Map<String,Object> result = success();
		return result;
	}

	/**
	 * 提现处理
	 * @param id
	 * @param uid 客户ID
	 * @param bankName 银行名称
	 * @param bankCardNumber 银行卡号
	 * @param amount 提现金额
	 * @param tradePassword 交易密码
	 * @return
	 */
	@RequestMapping("my/withdraw")
	public Map<String, Object> withdraw(			
			@RequestHeader(required = false) String uid,
			@RequestParam(value="bank_name", required = false) String bankName,
			@RequestParam(value="card_number", required = false) String bankCardNumber,
			String amount, 
			@RequestParam(value="trade_password", required = false) String tradePassword) {
		
		if (StringUtils.isBlank(uid)|| StringUtils.isBlank(bankCardNumber) || StringUtils.isBlank(amount)
				|| StringUtils.isBlank(tradePassword)) {
			return failure(ResultCode.MISSING_PARAMS);
		}
		
		//验证交易密码是否正确
		try {
			MemberSecurity memberSecurity = memberSecurityService.get(uid);
			if (memberSecurity != null) {
				if (!Encrypt.validatePassword(memberSecurity.getTradePassword(),
						tradePassword)) {
					return failure(ResultCode.INVALID_PASSWORD);
				}
			}
			
			//验证成功后，插入withdrawal表
			//当前卡可提现金额超限 add by David 2015/04/15 start
			BankCardCashio bankCardCashio=bankCardCashioService.findBycardnumber(uid, bankCardNumber, 0);
			Account account=accountService.getInfoBymemberId(uid);			
			if(Double.parseDouble(amount) > (bankCardCashio.getCashIn() - bankCardCashio.getCashOut() + account.getTotalProfit())){
				return failure(ResultCode.EXCEED_WITHDRAW_AMOUNT);
			}
			//add by David 2015/04/15 end
			//返回用户信息，获取户名
			Member member = memberService.get(uid); 
			//获取account_id
//			Account account = accountService.getInfoBymemberId(uid);
			//格式化当前时间,得到后加6位随机数
			Date date =DateUtils.getCurrentTime();
			SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
			String serialNumber = df.format(date).toString() + String.valueOf(Math.random()).substring(2,8);
			Withdrawal withdrawal = new Withdrawal();
			withdrawal.setSerialNumber(serialNumber);
			withdrawal.setMemberId(uid);
			withdrawal.setAccountId(account.getId());
			withdrawal.setCardNumbert(bankCardNumber);
			withdrawal.setAccountTitle(member.getRealName());
			withdrawal.setAmount(Double.parseDouble(amount));
			withdrawal.setStatus(Withdrawal.WAIT_AUDIT);
			withdrawal.setApplyDate(DateUtils.getCurrentTime());
//			withdrawalService.save(withdrawal);
			
			//更新account表内的可用余额和账面余额
			account.setBookBalance(account.getBookBalance()-Double.parseDouble(amount));
			account.setAvaliableBalance(account.getAvaliableBalance()-Double.parseDouble(amount));
//			accountService.save(account);
			
			//插入notes_book表
			NotesBook notesBook = new NotesBook();
//			notesBook.setAccount(account.getNumber());
//			//提现表示为C
//			notesBook.setDrcr(NotesBook.CR);
//			notesBook.setAmount(Double.parseDouble(amount));
//			notesBook.setBalance(account.getBookBalance());
//			notesBook.setCardNumber(bankCardNumber);
//			notesBook.setSerialNumber(serialNumber);
//			notesBook.setTxnDate(DateUtils.getCurrentTime());
//			notesBook.setType(NotesBook.TYPE_WITHDRAWAL);
//			notesBookService.save(notesBook);
			memberManager.withdraw(withdrawal,account,notesBook);
		} catch (Exception e) {
			logger.error(e.toString());
			return failure(ResultCode.WITHDRAW_ERROR);
		}
		
		return success();
	}
	/**
	 * 还款处理
	 * @param memberId
     * @param year
     * @param month
     * @param repaymentAmount
	 * @return
	 */
	@RequestMapping("my/payback")
	public Map<String, Object> payback(			
			@RequestHeader(required = false) String uid,
			int year,
			int month, 
			String amount,
			@RequestParam(value="trade_password", required = false) String tradePassword
			) {
		
		if (StringUtils.isBlank(uid)|| StringUtils.isBlank(tradePassword)) {
			return failure(ResultCode.MISSING_PARAMS);
		}
		//验证交易密码是否正确
		try {
			MemberSecurity memberSecurity = memberSecurityService.get(uid);
			if (memberSecurity != null) {
				if (!Encrypt.validatePassword(memberSecurity.getTradePassword(),
						tradePassword)) {
					return failure(ResultCode.INVALID_PASSWORD);
				}
			}
			//
			Account account = MemberUtils.getAccount(uid);
			
			accountManager.transferOut(account, RZContents.CHANNEL_ID, Double.parseDouble(amount), NotesBook.TYPE_REPAYMENT_PRINCIPLE, "还款");
			//
			feeManager.payback(uid, year, month, Double.parseDouble(amount));
		} catch (Exception e) {
			logger.error(e.toString());
			return failure(ResultCode.PAYBACK_ERROR);
		}
		
		return success();
	}
}
